import React, { Component } from "react";
// propTypes
import PropTypes from 'prop-types';
// antd
import { Form, Input, Button, Select, InputNumber, Radio, DatePicker } from "antd";
// components
import SelectComponent from "../select/Index";
import RadioComponent from "../radioButton/Index";
// store
import Store from "@/stroe/Index";
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

class FormSearch extends Component {

    constructor(props){
        super(props);
        this.state = {
            loading: false,
            // 获取RangePicker组件的值
            timeRange_string: '',
            mesPreix: {
                "Input": "请输入",
                "Radio": "请选择",
                "Select": "请选择",
                "SelectComponent": "请选择",
            }
        }
    }  

    UNSAFE_componentWillReceiveProps({ formConfig }){
        this.refs.form.setFieldsValue(formConfig.setFieldValue)
    }

    rules = (item) => {
        // state
        const { mesPreix } = this.state;
        let rules = [];
        // 是否必填
        if(item.required) {
            let message = item.message || `${mesPreix[item.type]}${item.label}`; // 请输入xxxxx，请选择xxxxxx
            rules.push({ required: true, message })
        }
        if(item.rules && item.rules.length > 0) {
            rules = rules.concat(item.rules);
        }
        return rules;
    }

    // input
    inputElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <Input allowClear style={item.style} placeholder={item.placeholder}/>
            </Form.Item>
        )
    }
    // input
    inputNumberElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <InputNumber min={item.min} max={item.max} />
            </Form.Item>
        )
    }
    // select
    selectElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <Select style={item.style} placeholder={item.placeholder} allowClear>
                    {
                        item.options && item.options.map(elem => {
                            return <Option value={elem.value} key={elem.value}>{elem.label}</Option>
                        })
                    }
                </Select>
            </Form.Item>
        )
    }
    // SelectComponent
    SelectComponent = (item) => {
        const rules = this.rules(item);
        console.log('Formsearch-SelectComponent=======>', item)
        console.log(item)
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={[...rules, {validator: this.validatorComponents}]}>
                <SelectComponent 
                    style={item.style} 
                    url={item.url} 
                    method={item.method} 
                    placeholder={item.placeholder} 
                    propsKey={item.propsKey} 
                    name={item.name} 
                    defaultValue={item.defaultValue}
                    initValue={this.props.formConfig.setFieldValue} 
                />
            </Form.Item>
        )
    }
    // RadioComponent
    RadioComponent = (item) => {
        const rules = this.rules(item);
        console.log('Formsearch-RadioComponent=====>', item)
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={[...rules]}>
                <RadioComponent 
                    style={item.style} 
                    url={item.url} 
                    method={item.method} 
                    placeholder={item.placeholder} 
                    propsKey={item.propsKey} 
                    name={item.name} 
                    initValue={this.props.formConfig.setFieldValue} 
                />
            </Form.Item>
        )
    }
    // radio
    radioElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <Radio.Group>
                    {
                        item.options && item.options.map(elem => {
                            return <Radio value={elem.value} key={elem.value}>{elem.label}</Radio>
                        })
                    }
                </Radio.Group>
            </Form.Item>
        )
    }
    // radio button
    radioButtonElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <Radio.Group buttonStyle="solid">
                    {
                        item.options && item.options.map(elem => {
                            return <Radio.Button size='small' value={elem.value} key={elem.value}>{elem.label}</Radio.Button>
                        })
                    }
                </Radio.Group>
            </Form.Item>
        )
    }
    // datePicker
    handleRangeChange = (value, dateString) => {
        console.log(value, dateString)
        this.setState({
            timeRange_string: dateString.toString()
        })
    }
    datePickerElem = (item) => {
        const rules = this.rules(item);
        return (
            <Form.Item label={item.label} name={item.name} key={item.name} rules={rules}>
                <RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    onChange={this.handleRangeChange}
                    ranges={{
                        'Today': [moment(), moment()],
                        'This Week': [moment().startOf('week'), moment().endOf('week')],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                    }}
                />
            </Form.Item>
        )
    }

    // 初始化
    initFormItem = () => {
        const { formItem } = this.props;
        // 检测是否存在 formItem
        if(!formItem || (formItem && formItem.length === 0)) { return false; }
        // 循环处理
        const formList = []
        formItem.forEach(item => {
            if(item.type === "Input") { formList.push(this.inputElem(item)); }
            if(item.type === "Select") { 
                item.options = Store.getState().config[item.optionsKey];
                formList.push(this.selectElem(item));
            }
            if(item.type === "SelectComponent") { formList.push(this.SelectComponent(item)); }
            if(item.type === "RadioComponent") { formList.push(this.RadioComponent(item)); }
            if(item.type === "InputNumber") { formList.push(this.inputNumberElem(item)); }
            if(item.type === "Radio") { formList.push(this.radioElem(item)); }
            if(item.type === "RadioButton") { formList.push(this.radioButtonElem(item)); }
            if(item.type === "DatePicker") { formList.push(this.datePickerElem(item)); }
        })
        console.log('formsearch===formList====>', formList)
        return formList;
    }

    onSubmit = (value) => {  // 添加、修改
        console.log('search submit======>', value)
        const searchData = {};
        for(let key in value) {
            console.log('key', key)
            if (key === 'time_range') {
                console.log(this.state)
                value[key] = this.state.timeRange_string; // 替换RangePicker组件的默认取值
            //     let time_moment = value[key];
            //     let new_time_range = [];
            //     time_moment.forEach((item)=>{
            //         const time_format = moment(item).format('YYYY-MM-DD HH:mm:ss')
            //         console.log(time_format)
            //         new_time_range.push(time_format)
            //     });
            //     value[key] = new_time_range;
            //     console.log('search submit222======>', value)
            }
            
            if(value[key] !== undefined && value[key] !== "") {
                searchData[key] = value[key]
            }
        }
        this.props.search(searchData)
    }

    render(){
        return (
            <Form layout="inline" ref="form" onFinish={this.onSubmit} initialValues={this.props.formConfig.initValue} {...this.props.formLayout}>
                { this.initFormItem() }
                { this.initFormItem() ?
                <Form.Item>
                    <Button loading={this.state.loading} type="primary" htmlType="submit">搜索</Button>
                </Form.Item> : ''}
            </Form>
        )
    }
}

// 校验数据类型
FormSearch.propTypes = {
    formConfig: PropTypes.object
}
// 默认
FormSearch.defaultProps = {
    formConfig: {}
}
export default FormSearch;